<!--
 * @Author: coman
 * @LastEditors: coman
 * @Date: 2020-06-23 19:56:23
 * @motto: No pain,No gain
 * @LastEditTime: 2020-06-23 21:00:44
--> 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 200px;
            height: 250px;
            background: orchid;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        // 拿到box选择器
        var box = document.querySelector("#box");
        // 获取鼠标在窗口的位置
        box.onmousedown=function(){
            window.onmousemove=function(e){
                e = e || window.event;
                var x = e.clientX;
                var y = e.clientY;
                    
                    if(x>=(window.innerWidth-box.offsetWidth/2)){
                        x=window.innerWidth-box.offsetWidth/2;
                  
    
                   }else if(x<=box.offsetWidth/2){
                       x=box.offsetWidth/2;
                   }
                     
                   if(y>=(window.innerHeight-box.offsetHeight/2)){
                        y=window.innerHeight-box.offsetHeight/2;
                        
    
                   }else if(y<=box.offsetHeight/2){
                       y=box.offsetHeight/2;
                   }
                    box.style.left=(x-box.offsetWidth/2)+"px";
                    box.style.top=(y-box.offsetHeight/2)+"px";
                    // if(box.offsetLeft>=(window.innerWidth-box.offsetWidth)){
                    //    box.offsetLeft=window.innerWidth-box.offsetWidth
                    // }
            }
            
        }
        // 鼠标抬起,停止移动
      onmouseup=function(){
         onmousemove=null;
      }
    </script>
</body>
</html>